import 'dart:convert';
import 'dart:io';

import 'package:cher_flare/utils/translate/ly_translate_model.dart';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/foundation.dart';

import '../../config/config.dart';

class LYTranslateManager {
  LYTranslateManager._internal();
  static final LYTranslateManager _instance = LYTranslateManager._internal();
  static LYTranslateManager get share {
    return _instance;
  }

  final translateUrl =
      "https://translation.googleapis.com/language/translate/v2";

  Future<String> translate({
    required String content,
    String? toLan,
    String? fromLan,
  }) async {
    final toCode = toLan ?? Config.lanCode;
    var urlParams = {
      "key": Config.googleTranslationKey,
      "target": toCode, // 目标语言Code，从设备中获取当前语言。
      "q": content, // 被翻译的文案
      "format": 'text',
    };

    debugPrint('$urlParams');
    try {
      Dio dio = Dio(BaseOptions(
          connectTimeout: const Duration(seconds: 10),
          receiveTimeout: const Duration(seconds: 10),
          contentType: 'application/json',
          responseType: ResponseType.json));
      final response = await dio.post(translateUrl,
          queryParameters: {
            "key": Config.googleTranslationKey,
            "target": toCode,
            "format": 'text',
          },
          data: urlParams);
      debugPrint("=response===${response.data}");
      if (response.data is Map) {
        final json = response.data['data'];
        final model = LYTranslateModel.fromJson(json);
        debugPrint("=translatedText===${model.translations}");
        return model.translations?.first.translatedText ?? '';
      }
      return "";
    } catch (e) {
      debugPrint("==error==$e}");
      return "";
    }
  }
}
